package com.visionvera.retrofitservice.net;

import com.trello.rxlifecycle2.LifecycleProvider;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by dongyukun on 2017/11/30.
 */

public class NetworkRequest {
    private static NetworkRequest mNetworkRequest;
    private NetworkRequest(){}
    public static NetworkRequest getInstance() {
        if (mNetworkRequest == null) {
            synchronized (NetworkRequest.class) {
                if (mNetworkRequest == null)
                    mNetworkRequest = new NetworkRequest();
            }
        }
        return mNetworkRequest;
    }

    public final Object getServiceInstance() {
        return RetrofitFactory.getInstance().getServerAPI();
    }

    public final <T, E> void subscribe(LifecycleProvider<E> lifecycleProvider, Observable<T> observable, BaseObserver<T> subscriber) {
        if (observable == null || subscriber == null) return;
        observable
                .map(new ResponseFunc())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(lifecycleProvider.<T>bindToLifecycle())
                .subscribe(subscriber);
    }
}
